﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.LowPriceHouse.Controllers
{
    [Description("低价房小区")]
    public class LowPriceHouseBuildingsController : BaseController
    {
        public ILowPriceHouseBuildingsContract LowPriceHouseBuildingsContract { get; set; }
        public IAreaContract AreaContract { set; get; }
        public ILowPriceHousesContract LowPriceHousesContract { set; get; }

        #region 列表
        [Description("低价房小区-列表")]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        { 
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket); 
            var query = from l in LowPriceHouseBuildingsContract.TrackEntities
                        join b in LowPriceHousesContract.TrackEntities
                        on l.Id equals b.LowPriceHouseBuildingID
                        where b.AgentID == model.AgentId
                        select new
                        {
                            Id = l.Id,
                            Name = l.Name,
                            ProvinceID = (from a in AreaContract.TrackEntities where a.Id == l.ProvinceID && a.AreaLevel == 1 select a.Name).FirstOrDefault(),
                            CityID = (from a in AreaContract.TrackEntities where a.Id == l.CityID && a.AreaLevel == 2 select a.Name).FirstOrDefault(),
                            AreaID = (from a in AreaContract.TrackEntities where a.Id == l.AreaID && a.AreaLevel == 3 select a.Name).FirstOrDefault(),
                            Address = l.Address,
                            Remark = l.Remark,
                            OpeningTime = l.OpeningTime,
                            LaunchTime = l.LaunchTime,
                            Developer = l.Developer,
                            DeveloperBrand = l.DeveloperBrand,
                            PropertyManagementCompany = l.PropertyManagementCompany,
                            PropertyManagementFee = l.PropertyManagementFee,
                            CoveredArea = l.CoveredArea,
                            TotalHouseholds = l.TotalHouseholds,
                            PlotRatio = l.PlotRatio,
                            GreeningRatio = l.GreeningRatio,
                            CarNumber = l.CarNumber,
                            ParkingRatio = l.ParkingRatio,
                            PriceAdvantage = l.PriceAdvantage,
                            HouseTypeArea = l.HouseTypeArea,
                            LivingFacilities = l.LivingFacilities,
                            SchoolDistrict = l.SchoolDistrict,
                            Transportation = l.Transportation,
                            RegionalDevelopment = l.RegionalDevelopment,
                            Characteristic = l.Characteristic,
                            BrandAdvantage = l.BrandAdvantage,
                            HaveProductComparison = l.HaveProductComparison,
                            X = l.X,
                            Y = l.Y,
                        };
            

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search));
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd");
        }
        #endregion

        #region 添加
        [Description("低价房小区-添加")]
        public ActionResult Insert()
        {
            return View();
        }
        [HttpPost]
        public ActionResult InsertAsync(LowPriceHouseBuildings entity)
        {
            #region 所有string为null的赋值""
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.ProvinceID == null)
            {
                entity.ProvinceID = "";
            }
            if (entity.CityID == null)
            {
                entity.CityID = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var count = LowPriceHouseBuildingsContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
             catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            var entity = LowPriceHouseBuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditAsync(LowPriceHouseBuildings entity)
        {
            #region 所有string为null的赋值""
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.ProvinceID == null)
            {
                entity.ProvinceID = "";
            }
            if (entity.CityID == null)
            {
                entity.CityID = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var count = LowPriceHouseBuildingsContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 删除
        [Description("广告-删除")]
        [HttpPost]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                for (int i = 0; i < idsInt.Length; i++)
                {
                    LowPriceHouseBuildingsContract.Delete(idsInt[0]);
                }

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 地图坐标
        public ActionResult EditMapCoordinate(int id)
        {
            var entity = LowPriceHouseBuildingsContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditMapCoordinateAsync(LowPriceHouseBuildings entity)
        {
            #region 所有string为null的赋值""
            if (entity.Name == null)
            {
                entity.Name = "";
            }
            if (entity.ProvinceID == null)
            {
                entity.ProvinceID = "";
            }
            if (entity.CityID == null)
            {
                entity.CityID = "";
            }
            if (entity.AreaID == null)
            {
                entity.AreaID = "";
            }
            if (entity.Address == null)
            {
                entity.Address = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.Developer == null)
            {
                entity.Developer = "";
            }
            if (entity.DeveloperBrand == null)
            {
                entity.DeveloperBrand = "";
            }
            if (entity.PropertyManagementCompany == null)
            {
                entity.PropertyManagementCompany = "";
            }
            if (entity.PropertyManagementFee == null)
            {
                entity.PropertyManagementFee = "";
            }
            if (entity.CoveredArea == null)
            {
                entity.CoveredArea = "";
            }
            if (entity.TotalHouseholds == null)
            {
                entity.TotalHouseholds = "";
            }
            if (entity.PlotRatio == null)
            {
                entity.PlotRatio = "";
            }
            if (entity.GreeningRatio == null)
            {
                entity.GreeningRatio = "";
            }
            if (entity.CarNumber == null)
            {
                entity.CarNumber = "";
            }
            if (entity.ParkingRatio == null)
            {
                entity.ParkingRatio = "";
            }
            if (entity.PriceAdvantage == null)
            {
                entity.PriceAdvantage = "";
            }
            if (entity.HouseTypeArea == null)
            {
                entity.HouseTypeArea = "";
            }
            if (entity.LivingFacilities == null)
            {
                entity.LivingFacilities = "";
            }
            if (entity.SchoolDistrict == null)
            {
                entity.SchoolDistrict = "";
            }
            if (entity.Transportation == null)
            {
                entity.Transportation = "";
            }
            if (entity.RegionalDevelopment == null)
            {
                entity.RegionalDevelopment = "";
            }
            if (entity.Characteristic == null)
            {
                entity.Characteristic = "";
            }
            if (entity.BrandAdvantage == null)
            {
                entity.BrandAdvantage = "";
            }
            if (entity.HaveProductComparison == null)
            {
                entity.HaveProductComparison = "";
            }
            #endregion
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                var count = LowPriceHouseBuildingsContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 获取省属区
        /// <summary>  
        /// 获取省份  
        /// </summary>  
        [AjaxOnly]
        public ActionResult GetProvincelist()
        {
            //获取省份数据   
            var queryResult = AreaContract.TrackEntities.Where(a => a.AreaLevel == 1);
            return JsonEx(queryResult.ToList(), JsonRequestBehavior.AllowGet);
        }
        /// <summary>  
        /// 获取城市  
        /// </summary>  
        /// <param name="pid"></param>  
        /// <returns></returns>  
        [AjaxOnly]
        public ActionResult GetCitylist(string pid)//根据省份ID获取城市  
        {
            pid = pid.Trim();
            var list = AreaContract.TrackEntities.Where(m => m.ParentID.Equals(pid)).ToList();//城市ID对应值  
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        [AjaxOnly]
        /// <summary>  
        /// 获取区
        /// </summary>  
        /// <param name="cid"></param>  
        /// <returns></returns>  
        public ActionResult GetDistrictlist(string cid)//根据城市ID获取区县ID  
        {
            cid = cid.Trim();
            var list = AreaContract.TrackEntities.Where(a => a.ParentID.Equals(cid)).ToList();//区县ID对应值 
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}